package com.itheima.health.config;

import com.itheima.health.security.HealthUserServiceDetailsImpl;
import com.itheima.health.security.JWTAuthenticationFilter;
import com.itheima.health.security.JWTAuthorizationFilter;
import com.itheima.health.security.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 对密码进行加密
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启权限注解
@EnableConfigurationProperties(JwtProperties.class)
public class HealthWebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private HealthUserServiceDetailsImpl healthUserServiceDetails;
    @Autowired
    private JwtProperties properties;

    /**
     * 密码加密 passwordEncode 密码加密
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库版
        auth.userDetailsService(healthUserServiceDetails).passwordEncoder(createPasswordEncode());

        //System.out.println(createPasswordEncode().encode("1234"));
        //内存版
//    auth.inMemoryAuthentication().passwordEncoder(createPasswordEncode()).
//            withUser("lilei").password(createPasswordEncode().encode("1234")).
//            roles("ADMIN").and()
//            .withUser("marry").password(createPasswordEncode().encode("1234"))
//            .roles("CHECKITEM_QUERY","CHECKITEM_DELETE","query");
    }

    /**
     * 对密码进行加密
     * @return
     */
    @Bean
    public PasswordEncoder createPasswordEncode(){
        return new BCryptPasswordEncoder();
    }


    /**
     * 配置不需要认证的资源，浏览器可以直接访问
     * @param web
     * @throws Exception
     */
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//
//        web.ignoring().mvcMatchers("/css/**","/js/**","/login.html");
//
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        //跳转到登录页面
//        http.formLogin().loginPage("/login.html").//定义自己的的登录页面
//                loginProcessingUrl("/login.do").//重写过滤器UsernamePasswordAuthenticationFilter处理登录请求地址
//                usernameParameter("name")
//                .defaultSuccessUrl("/pages/index.html",true)//认证成功，跳转页面
//                .failureUrl("/login.html").//认证失败  跳转登录
//                and().authorizeRequests().
//                antMatchers("/pages/delete.html").
//                hasRole("ADMIN").
//                antMatchers("/pages/query.html").hasRole("query")
//                .antMatchers("/pages/**").authenticated().
//                and().exceptionHandling().accessDeniedPage("/error.html").
//                and().logout().logoutUrl("/logout.do").logoutSuccessUrl("/login.html").
//                invalidateHttpSession(true).//禁用session
//                and().csrf().disable();

        http.csrf().//禁用csrf
                disable().
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))//启用过滤器
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session

    }
}
